﻿// Decompiled with JetBrains decompiler
// Type: MCM.Internal.GameFeatures.PerSaveCampaignBehavior
// Assembly: MCMv5, Version=5.10.2.0, Culture=neutral, PublicKeyToken=null
// MVID: 7AB326B9-B2B4-41C2-9177-68E944071101
// Assembly location: D:\steam\steamapps\workshop\content\261550\2859238197\bin\Win64_Shipping_Client\MCMv5.dll

using BUTR.DependencyInjection;
using MCM.Abstractions.Base;
using MCM.Abstractions.Base.PerSave;
using MCM.Abstractions.GameFeatures;
using MCM.Implementation;
using MCM.Implementation.PerSave;
using System;
using System.Collections.Generic;
using System.IO;
using TaleWorlds.CampaignSystem;

#nullable enable
namespace MCM.Internal.GameFeatures
{
  internal sealed class PerSaveCampaignBehavior : CampaignBehaviorBase, IPerSaveSettingsProvider
  {
    private Dictionary<string, string>? _settings = new Dictionary<string, string>();

    public Dictionary<string, string>? Settings => this._settings;

    public override void SyncData(IDataStore dataStore)
    {
      dataStore.SyncData<Dictionary<string, string>>("_settings", ref this._settings);
      if (!dataStore.IsLoading)
        return;
      if (this._settings == null)
        this._settings = new Dictionary<string, string>();
      GenericServiceProvider.GetService<PerSaveSettingsContainer>()?.LoadSettings();
    }

    public override void RegisterEvents()
    {
      CampaignEvents.OnNewGameCreatedEvent.AddNonSerializedListener((object) this, new Action<CampaignGameStarter>(this.OnNewGameCreatedEvent));
    }

    private void OnNewGameCreatedEvent(CampaignGameStarter campaignGameStarter)
    {
      this._settings = new Dictionary<string, string>();
      GenericServiceProvider.GetService<PerSaveSettingsContainer>()?.LoadSettings();
    }

    public bool SaveSettings(PerSaveSettings perSaveSettings)
    {
      JsonSettingsFormat service = GenericServiceProvider.GetService<JsonSettingsFormat>();
      if (this._settings == null || service == null)
        return false;
      this._settings[Path.Combine(perSaveSettings.FolderName, perSaveSettings.SubFolder, perSaveSettings.Id) ?? ""] = service.SaveJson((BaseSettings) perSaveSettings);
      return true;
    }

    public void LoadSettings(PerSaveSettings perSaveSettings)
    {
      JsonSettingsFormat service = GenericServiceProvider.GetService<JsonSettingsFormat>();
      string content;
      if (this._settings == null || service == null || !this._settings.TryGetValue(Path.Combine(perSaveSettings.FolderName, perSaveSettings.SubFolder, perSaveSettings.Id) ?? "", out content))
        return;
      service.LoadFromJson((BaseSettings) perSaveSettings, content);
    }
  }
}
